package com.unitd.filesystem.utils;

import com.alibaba.fastjson.JSON;
import com.unitd.filesystem.comm.FileItem;
import com.unitd.filesystem.comm.FileType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @desc 从互联网上下载文件的工具帮助类
 * @filename HttpDownloadHelper.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/3/6
 */
public class HttpDownloadHelper {

	/** http客户端 */
	private static OkHttpClient httpClient = new OkHttpClient();

	/**
	 * @desc 从指定URL读取文件信息
	 * @param url 文件URL
	 * @return FileItem
	 */
	public static FileItem read(String url) throws IOException {
		FileItem item = new FileItem();
		Request.Builder requestBuilder = new Request.Builder().url(url);
		Response response = httpClient.newCall(requestBuilder.build()).execute();

		item.setFileType(HttpFilePathHelper.parseFileType(url));
		item.setDatas(response.body().bytes());
		if (item.getFileType() == null) {
			item.setFileType(FileType.getFileSuffix(item.getDatas()));
		}
		item.setUrl(url);
		return item;
	}

	public static void main(String[] args) {
		String remoteURL = "http://avatar.csdn.net/E/8/1/1_u010388497.jpg";
		try {
			System.out.println(JSON.toJSON(read(remoteURL)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}